import React from 'react'
import { ImgTxt, NavContent, Link } from '../../ui-components'
import { u } from '../../actions/util'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as homeAction from '../../actions/home.action'
import { fileUpload } from '../../actions/file.action'
import style from './style.styl'
import util from '../../util'
import cx from 'classnames'
import moment from 'moment'

moment.locale('zh-cn')

/*
const HR = {
  name: '人事流程',
  children: [
    {
      name: '入职管理',
      url: '#/reorg/onboarding/hr/onboardingFlows?hasApproved=0',
      icon: 'hr'
    },
    {
      name: '转正管理',
      url: '#/reorg/employ-managements/1',
      icon: 'hr'
    },
    {
      name: '调岗管理',
      url: '#/reorg/transfer',
      icon: 'hr'
    },
    {
      name: '离职管理',
      url: '#/reorg/employ-managements/2',
      icon: 'hr'
    }
  ]
}
*/

const OKR = {
  name: '目标',
  children: [
    {
      name: '我的目标',
      url: '#/okr?type=3',
      icon: 'myObjective'
    },
    {
      name: '团队目标',
      url: '#/okr?type=2',
      icon: 'teamObjective'
    },
    {
      name: '公司目标',
      url: '#/okr?type=1',
      icon: 'orgObjective'
    }
  ]
}

const REVIEW = {
  name: '反馈',
  children: [
    {
      name: '反馈给同事',
      url: '#/review/peer',
      icon: 'feedbackToWorkmate'
    },
    {
      name: '接受反馈',
      url: '#/review/self',
      icon: 'getFeedback'
    },
    {
      name: '反馈活动管理',
      url: '#/review/admin',
      icon: 'hr'
    }
  ]
}

/*
const SYSTEM = {
  name: '系统配置',
  children: [
    {
      name: '公司设置',
      url: '#/system/companySettings',
      icon: 'admin'
    },
    {
      name: '员工档案设置',
      url: '#/system/profileSettings',
      icon: 'admin'
    },
    {
      name: '批量上传档案',
      url: '#/system/uploadProfile',
      icon: 'admin'
    }
  ]
}
*/

function pickNav(obj, from, to) {
  return {
    ...obj,
    children: obj.children.slice(from, to == null? from +1: to)
  }
}

function Nav(props) {

  const { teamVO } = props.profile

  const GROUPS =  {
    name: '团队',
    children: [
      {
        name: '浏览团队',
        url: (teamVO || {}).teamId? `#/team/myTeam?teamId=${teamVO.teamId}`: null,
        icon: 'viewTeam'
      },
      {
        name: '汇报关系管理',
        url: '#/team/relationManage',
        icon: 'hr'
      },
      {
        name: '组织架构管理',
        url: '#/team/teamManage',
        icon: 'hr'
      }
    ]
  }


  const { roleNameList=[],reporterFullName } = props.profile
  if (!roleNameList.length) return null

  let _REVIEW = reporterFullName? REVIEW: {...REVIEW, children: [REVIEW.children[0], REVIEW.children[2]]}

  let navs = []
  if (~roleNameList.indexOf('staff')) navs= [ pickNav(GROUPS, 0), OKR, pickNav(_REVIEW, 0, reporterFullName ? 2 : 1) ]
    //if (~roleNameList.indexOf('HR')) navs = [ GROUPS, HR, OKR, _REVIEW ]
    //if (~roleNameList.indexOf('orgAdmin')) navs = [ ...navs,  SYSTEM ]

  return (
    <div className={style.nav}>
      <header>
        <ImgTxt
          className={style['avatar']}
          width="60"
          big
          src={props.profile.avatarUrl}
          name={props.profile.fullName}
          title={props.profile.jobTitleName}
        />
      </header>
      <section className={style.list}>
        {
          navs.map((item, i) => (
            <div key={i} className={cx(style.group, { [style.short]: item.name.length == 2 })}>
              <header>{ item.name }</header>
              {
                item.children? (
                  <ul className={style.children}>
                    {
                      item.children.map((v, i) => (
                        <li key={i}>
                          <Link to={v.url} color="blue" label={v.name} icon={v.icon}/>
                        </li>
                      ))
                    }
                  </ul>
                ): null
              }
            </div>
          ))
        }
      </section>
    </div>
  )
}

function RightList() {
  return (
    <div className={style['right-list']}>
    </div>
  )
}


export default
@connect(({ app, home }) => ({ app, home }), dispatch => ({actions: bindActionCreators({ ...homeAction, fileUpload }, dispatch)}))
class Home extends React.Component {

	static contextTypes = {
		router: React.PropTypes.object
	}

  renderNewStaffs() {
    const { teamVO } = this.props.app.org
    return this.renderRightList({
      list: this.props.home.newStaffs,
      label: '新同事',
      more: {
        to: `#/team/myTeam?teamId=${(teamVO || {}).teamId}`
      }
    })
  }

  renderEnrollAnniversary() {
    return this.renderRightList({
      list: this.props.home.enrollAnniversary,
      label: '周年纪念'
    })
  }

  getDayInYear(time) {
    var dateArr = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    var date = time? new Date(time): new Date();
    var day = date.getDate();
    var month = date.getMonth(); //getMonth()是从0开始
    var year = date.getFullYear();
    var result = 0;
    for (var i = 0; i < month; i++) {
      result += dateArr[i];
    }
    result += day;
    /*
    //判断是否闰年
    if (month > 1 && (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
      result += 1;
    }
    */
    return result
  }

  countAnni(time) {
    const prevDay = this.getDayInYear(time)
    const nowDay = this.getDayInYear()

    const d = nowDay - prevDay

    if (d < 0) {
      // 12月份入职
      if (Math.abs(d) < 20) return `${-d}天后`;
      else return `${365 - Math.abs(d)}天前`;
    }
    else if (d == 0) {
      return '今天';
    }
    else {
      // 1月份后入职
      if (d > 345) return `${365 - d}天后`;
      else return `${d}天前`;
    }
  }
  
  renderRightItemTime(label, v) {
    if(label === '周年纪念') return this.countAnni(v.enrollDate)
    const d = new Date(v.enrollDate);
    const now = new Date();
    if (d.getFullYear() == now.getFullYear() && d.getMonth() == now.getMonth() && d.getDate() == now.getDate()) {
      return '今天';
    }
    return moment(v.enrollDate).fromNow() 
  }

  renderRightList({ list, more, label }) {
    if (util.isNull(list)) return null
    return (
      <div>
        <h2>
          <span>{ label }</span>
          {
            more?
            <Link to={more.to} label="[更多]"/>
            : null
          }
        </h2>
        <ul>
          {
            list.map((v, i) => (
              <li key={i}>
                <ImgTxt 
                  className={style['right-list-avatar']}
                  name={v.fullName}
                  title={v.jobTitleName}
                  src={v.avatarUrl}
                  to={`#/user/${v.userId}`}
                />
                <span>
                  { 
                    this.renderRightItemTime(label, v)
                  }
                </span>
              </li>
            ))
          }
        </ul>
      </div>
    )
  }

  componentDidMount() {
    this.props.actions.fetchNewStaffs()
    this.props.actions.fetchEnrollAnniversary()
    this.props.actions.fetchSidebar()
  }

  componentWillUnmount() {
    this.props.actions.resetHome()
  }

  render() {
    return (
      <div className={style.root}>
        {/*<div style={{ width: '175px' }}>
          <Nav {...this.props.app}/>
        </div>
        */}
        {
          React.Children.map(this.props.children, child => React.cloneElement(child, {
            ...this.props.actions,
            ...this.context,
            ...this.props.app,
            root: this.props.root
          }))
        }
        {/*<div className={style['right-list']}>
          { this.renderNewStaffs() }
          { this.renderEnrollAnniversary() }
        </div>*/}
        
      </div>
    )
  }
}
